package com.example.zbh.dsliao.model;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.easemob.EMCallBack;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.db.entity.UserContact;
import com.example.zbh.dsliao.model.modelinterface.ModelLoginInterface;
import com.example.zbh.dsliao.presenter.presenterinterface.PresenterRegisterInterface;
import com.example.zbh.dsliao.ui.activty.SetPersonnalActivity;
import com.example.zbh.dsliao.utils.DlUser;
import com.example.zbh.dsliao.utils.PreferenceHelper;
import com.example.zbh.dsliao.utils.UserProfileManager;
import com.example.zbh.dsliao.view.CustomDialog;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/11/18.
 */
public class LoginModel implements ModelLoginInterface {
    private String userName = null;
    private String psw = null;

    private PreferenceHelper preferenceHelper;


    public LoginModel() {
        preferenceHelper = PreferenceHelper.getInstance();
    }

    @Override
    public void checkLogInUser(Map<String, String> map, final PresenterRegisterInterface presenterRegisterInterface) {


        userName = map.get(Constant.USER_NAME);
        psw = map.get(Constant.USER_PSW);

        final Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case Constant.MSG_ONE:
                        presenterRegisterInterface.checkFailResult("用户名不能为空");
                        break;
                    case Constant.MSG_TWO:
                        presenterRegisterInterface.checkFailResult("密码不能为空");
                        break;
                    case Constant.MSG_THREE:
                        presenterRegisterInterface.checkResult("登录成功");
                        break;
                    case Constant.MSG_FOUR:
                        String s = msg.obj.toString();
                        presenterRegisterInterface.checkFailResult("登录失败" + s);
                        break;
                }
                return false;
            }
        });


        if (TextUtils.isEmpty(userName)) {
            handler.sendEmptyMessage(Constant.MSG_ONE);
            return;
        }
        if (TextUtils.isEmpty(psw)) {
            handler.sendEmptyMessage(Constant.MSG_TWO);
            return;
        }

        EMChatManager.getInstance().login(userName, psw, new EMCallBack() {
            @Override
            public void onSuccess() {
                //异步获取当前用户的昵称和头像(第三方服务器 非环信)
                UserProfileManager.asyncGetCurrentUserInfo();

                //第一次登录或者之前的退出后在登录,加载所有本地群和会话
                EMChatManager.getInstance().loadAllConversations();//会话
                EMGroupManager.getInstance().loadAllGroups();//群组
                handler.sendEmptyMessage(Constant.MSG_THREE);
                //登录成功之后使用用户名异步请求第三方服务器中对应的昵称和头像
                asyncFetchUserInfo(userName);
                DatabaseHelper.getInstance().deleteContactPeople();
                try {
                    List<String> list = EMChatManager.getInstance().getContactUserNames();
                    getContactInfos(list, new EMValueCallBack<List<UserContact>>() {
                        @Override
                        public void onSuccess(List<UserContact> list) {


                        }

                        @Override
                        public void onError(int i, String s) {

                        }
                    });
                } catch (EaseMobException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(int i, String s) {

                Message message = handler.obtainMessage();
                message.what = Constant.MSG_FOUR;
                message.obj = s;
                handler.sendMessage(message);

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    /**
     * 异步根据用户名请求第三方服务器对应的昵称 和头像
     **/
    private void asyncFetchUserInfo(String username) {
        UserProfileManager.asyncGetUserInfo(username, new EMValueCallBack<DlUser>() {
            @Override
            public void onSuccess(DlUser user) {
                if (user != null) {
//                    取当前缓存中的用户名和头像
                    String nowavater = preferenceHelper.getThreeCurrentUserAvatar();
                    String nowname = preferenceHelper.getThreeCurrentUserNick();
                    //判断请求回来的用户名和头像是否一致
                    //若一致则不操作
                    //若不一致则设置到缓存中
                    if (user.getNick() != null) {
                        if (user.getNick() != nowname) {
//                            请求成功之后设置到缓存中
                            preferenceHelper.setThreeCurrentUserNick(user.getNick());
                        }
                    }
                    if (user.getAvatar() != null) {
                        if (user.getAvatar() != nowavater) {
                            preferenceHelper.setThreeCurrentUserAvatar(user.getAvatar());
                        }
                    }
                    Log.d("gegege", user.getAvatar() + ">>>>>>>>>");
                    Log.d("gegege", user.getNick() + ">>>>>>>>>");
                }
            }

            @Override
            public void onError(int error, String errorMsg) {
            }
        });
    }


    //得到一群用户的信息
    public void getContactInfos(final List<String> usernames, final EMValueCallBack<List<UserContact>> callback) {

        ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("geanwen");
        pQuery.whereContainedIn("username", usernames);
        pQuery.findInBackground(new FindCallback<ParseObject>() {

            @Override
            public void done(List<ParseObject> arg0, ParseException arg1) {
                if (arg0 != null) {
                    List<UserContact> mList = new ArrayList<UserContact>();
                    for (int i = 0; i < arg0.size(); i++) {
                        UserContact user = new UserContact();
                        ParseFile parseFile = arg0.get(i).getParseFile("avatar");
                        if (parseFile != null) {
                            user.setAvatar(parseFile.getUrl());
                        }
                        user.setNickname(arg0.get(i).getString("nickname"));
                        user.setUsername(arg0.get(i).getString("username"));
                        mList.add(user);
                        Log.i("yaolin", user.getAvatar() + "++" + user.getNickname() + "++" + user.getUsername());
                    }
                        DatabaseHelper.getInstance().saveContactPeople(mList);

                } else {

                }
            }
        });
    }

}
